package org.bing.engine.console.message;

import java.util.Date;

import org.bing.engine.common.message.HandlerAdapter;
import org.bing.engine.common.message.Message;
import org.bing.engine.console.service.ControllerManager;
import org.bing.engine.core.domain.Controller;

public class ControllerBeatHandler extends HandlerAdapter {
    private ControllerManager controllerManager;

    public void setControllerManager(ControllerManager manager) {
        this.controllerManager = manager;
    }

    @Override
    protected Object doHandle(Message msg) {
        Object body = msg.getBody();
        if (body == null || !body.getClass().equals(Controller.class)) {
            logger.warn("Can't handle " + body);
            return null;
        }
        Controller controller = (Controller) body;
        Controller controllerDb = controllerManager.findByGlobalId(controller.getGlobalId());
        if (controllerDb != null) {
            copy(controller, controllerDb);
            controllerManager.save(controllerDb);
        } else {
            logger.info("Add new controller to console " + controller);
            controllerDb = controller;
            controllerManager.save(controllerDb);
        }
        return controllerDb;
    }

    private void copy(Controller src, Controller dest) {
        dest.setAddress(src.getAddress());
        dest.setHostname(src.getHostname());
        dest.setGateway(src.getGateway());
        dest.setLastActivityTime(new Date());
        dest.setPort(src.getPort());
        dest.setStartTime(src.getStartTime());
        dest.setVersion(src.getVersion());
    }
}
